package com.neusoft.demo.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.neusoft.demo.dao.GoodsMapper;
import com.neusoft.demo.dao.GouwucheMapper;
import com.neusoft.demo.po.Goods;
import com.neusoft.demo.po.Gouwuche;
import com.neusoft.demo.utils.SqlSessionFactoryUtil;

@WebServlet("/ChaGouWuCheServlet")
public class ChaGouWuCheServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 接收传来的商品id
		Integer goods_id = Integer.valueOf(request.getParameter("goods_id"));

		/*
		 * 由于没有登录，这里用户静态赋值：20
		 * 参考https://blog.csdn.net/u013475360/article/details/53376684
		 * 
		 * //返回与当前request相关联的session，如果没有则在服务器端创建一个 HttpSession httpSession
		 * =request.getSession(); //获取session httpSession.getAttribute("uid");
		 */
		Integer uid = 20;

		// 新建购物车实体类，并赋值
		Gouwuche gouwuche = new Gouwuche();
		gouwuche.setGoods_id(goods_id);
		gouwuche.setUid(uid);
		// 创建SqlSession对象
		SqlSession session = SqlSessionFactoryUtil.getSqlSessionFactory().openSession();
		// 生成代理类
		GouwucheMapper gouwucheMapper = session.getMapper(GouwucheMapper.class);
		// 获得商品的商品信息
		Gouwuche gouwuche1 = gouwucheMapper.findGouwucheByGoodsidUid(gouwuche);
		// 判断商品是否被加入过购物车
		if (gouwuche1 != null) {
			// 数量加一
			Integer num = gouwuche1.getNum();
			gouwuche1.setNum(num + 1);
			// 更新购物车
			gouwucheMapper.updateGouwuche(gouwuche1);
			// 提交事务
			session.commit();

		} else {
			// 生成代理类
			GoodsMapper goodsMapper = session.getMapper(GoodsMapper.class);
			// 获取商品信息
			Goods goods = goodsMapper.findOneGood(goods_id);
			gouwuche.setGoods_name(goods.getGoodsName());
			gouwuche.setCash(goods.getCash());
			gouwuche.setPic(goods.getPic());
			gouwuche.setNum(1);
			gouwuche.setSel(1);
			// 新增数据
			gouwucheMapper.insertGouwuche(gouwuche);
			// 提交事务
			session.commit();
		}

		session.close();
	}

}